//解析器

const NodeTypeElement = 1
const NodeTypeText = 3

class Complier {
  //需要传入 Wue实例
  constructor (wm) {
    this.$wm = wm
    this.$el = wm.$el
    this.complie(wm.$el)
  }

  complie (el) {
    Array.from(el.childNodes).forEach(node => {
      if (node.childNodes && node.childNodes.lenth != 0) {
        //有子节点的情况下遍历子节点
        this.complie(node)
      }
      //处理插值表达式
      if (this.isTextNode(node)) {
        this.complieText(node)
      }
      //处理指令
      if (this.isElementNode(node)) {
        this.complieElement(node)
      }
    })
  }

  //判断是否为文本节点
  isTextNode (node) {
    return node.nodeType === NodeTypeText
  }

  //判断是否为元素节点
  isElementNode (node) {
    return node.nodeType === NodeTypeElement
  }

  //判断是否属性是指令
  isDirective (attr) {
    return attr.startsWith('v-')
  }

  //解析插值表达式，将{{msg}} 替换为 wm.msg
  complieText (node) {
    let reg = /\{\{(.+)\}\}/
    let value = node.textContent
    if (reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.$wm[key])
      new Watcher(this.$wm,key,function(newValue){
        node.textContent = value.replace(reg,newValue)
      })
    }
  }

  //解析元素节点
  complieElement (node) {
    let attrs = node.attributes
    Array.from(attrs).forEach(attr => {
      if (this.isDirective(attr.name)) {
        let type = attr.name.slice(2) + 'Updater'
        this[type].call(this, node,attr)
      }
    })
  }

  // v-text处理  将属性值替换为data属性值
  textUpdater (node,attr) {
    node.textContent = this.$wm[attr.value]
    //创建watcher,进行视图更新
    new Watcher(this.$wm,attr.value,function(newValue){
      node.textContent = newValue
    })
  }

  // v-model处理
  modelUpdater (node,attr) {
    node.value = this.$wm[attr.value]
    new Watcher(this.$wm,attr.value,function(newValue){
      node.value = newValue
    })
    //双向数据绑定
    window.addEventListener('input',(event)=>{
      this.$wm[attr.value] = node.value
    })
  }
}
